home *** CD-ROM | disk | FTP | other *** search
/ Technotools / Technotools (Chestnut CD-ROM)(1993).ISO / lang_c / ctutor / tutor_c.doc
Text File  |  1986-07-28  |  63KB  |  1,876 lines

  1.  
  2.  
  3.                Programming in C _ A Tutorial
  4.  
  5.                      Brian W. Kernighan
  6.            Bell Laboratories, Murray Hill, N. J.
  7. 1.  Introduction.
  8.  
  9.      C is a computer language available on the GCOS and UNIX
  10. operating  systems  at Murray Hill and (in preliminary form)
  11. on OS/360 at  Holmdel.   C  lets  you  write  your  programs
  12. clearly  and  simply _ it has decent control flow facilities
  13. so your code can be read straight  down  the  page,  without
  14. labels  or  GOTO's;  it  lets you write code that is compact
  15. without being too cryptic; it encourages modularity and good
  16. program  organization; and it provides good data-structuring
  17. facilities.
  18.  
  19.      This memorandum is a tutorial to  make  learning  C  as
  20. painless  as  possible.   The first part concentrates on the
  21. central features of C; the second part discusses those parts
  22. of  the  language which are useful (usually for getting more
  23. efficient and smaller code) but which are not necessary  for
  24. the  new user.  This is "not" a reference manual.  Details and
  25. special cases will be skipped  ruthlessly,  and  no  attempt
  26. will  be made to cover every language feature.  The order of
  27. presentation is hopefully pedagogical  instead  of  logical.
  28. Users  who  would  like  the full story should consult the 'C
  29. Reference Manual' by D. M. Ritchie [1], which should be  read
  30. for details anyway.  Runtime support is described in [2] and
  31. [3]; you will have to read one of these to learn how to com-
  32. pile and run a C program.
  33.  
  34.      We will assume that you are familiar with the mysteries
  35. of creating files, text editing, and the like in the operat-
  36. ing system you run on, and that you have programmed in  some
  37. language before.
  38.  
  39.  
  40. 2. A Simple C Program
  41.  
  42.  
  43.      main( ) {
  44.              printf("hello, world");
  45.      }
  46.  
  47.  
  48.      A C program consists of one or  more  functions,  which
  49. are  similar  to  the functions and subroutines of a Fortran
  50. program or the procedures of PL/I, and perhaps some external
  51. data  definitions.  main is such a function, and in fact all
  52. C programs must have  a  main.   Execution  of  the  program
  53. begins  at  the  first statement of main.  main will usually
  54. invoke other functions to perform its job, some coming  from
  55. the same program, and others from libraries.
  56.  
  57.      One method of communicating data between  functions  is
  58. by  arguments.   The parentheses following the function name
  59. surround the argument list; here main is a  function  of  no
  60. arguments,  indicated by ( ).  The {} enclose the statements
  61. of the function.  Individual statements end with a semicolon
  62. but are otherwise free-format.
  63.  
  64.      printf is a library  function  which  will  format  and
  65. print  output on the terminal (unless some other destination
  66. is specified).  In this  case it prints
  67.  
  68.      hello, world
  69.  
  70. A function is invoked by naming it, followed by  a  list  of
  71. arguments  in parentheses.  There is no CALL statement as in
  72. Fortran or PL/I.
  73.  
  74. 3. A Working C Program; Variables; Types and Type Declarations
  75.  
  76.      Here's a bigger program that adds  three  integers  and
  77. prints their sum.
  78.  
  79.      main( ) {
  80.              int a, b, c, sum;
  81.              a = 1;  b = 2;  c = 3;
  82.              sum = a + b + c;
  83.              printf("sum is %d", sum);
  84.      }
  85.  
  86.  
  87.      Arithmetic and the assignment statements are  much  the
  88. same as in Fortran (except for the semicolons) or PL/I.  The
  89. format of C programs is quite  free.   We  can  put  several
  90. statements on a line if we want, or we can split a statement
  91. among several lines if it seems desirable. The split may  be
  92. between  any  of  the operators or variables, but NOT in the
  93. middle of a name or operator.  As a matter of style, spaces,
  94. tabs,  and  newlines should be used freely to enhance reada-
  95. bility.
  96.  
  97.      C has four fundamental types of variables:
  98.  
  99.  int     integer (PDP-11: 16 bits; H6070: 36 bits; IBM360: 32 bits)
  100.  char    one byte character (PDP-11, IBM360: 8 bits; H6070: 9 bits)
  101.  float   single-precision floating point
  102.  double  double-precision floating point
  103.  
  104. There are also arrays and structures of these  basic  types,
  105. pointers  to  them  and  functions  that return them, all of
  106. which we will meet shortly.
  107.  
  108.      All variables in a C program must be declared, although
  109. this  can sometimes be done implicitly by context.  Declara-
  110. tions must precede executable statements.  The declaration
  111.  
  112.      int a, b, c, sum;
  113.  
  114. declares a, b, c, and sum to be integers.
  115.  
  116.      Variable names have one  to  eight  characters,  chosen
  117. from  A-Z,  a-z,  0-9,  and  _,  and start with a non-digit.
  118. Stylistically, it's much better to use only  a  single  case
  119. and  give  functions  and  external variables names that are
  120. unique in the first six characters.  (Function and  external
  121. variable names are used by various assemblers, some of which
  122. are limited in the size and case  of  identifiers  they  can
  123. handle.)  Furthermore,  keywords  and  library functions may
  124. only be recognized in one case.
  125.  
  126. 4. Constants
  127.  
  128.      We have already seen decimal integer constants  in  the
  129. previous  example  _ 1, 2, and 3.  Since C is often used for
  130. system programming and bit-manipulation, octal  numbers  are
  131. an  important  part  of the language.  In C, any number that
  132. begins with 0 (zero!) is an octal integer (and  hence  can't
  133. have any 8's or 9's in it).  Thus 0777 is an octal constant,
  134. with decimal value 511.
  135.  
  136.      A ``character'' is one  byte  (an  inherently  machine-
  137. dependent concept).  Most often this is expressed as a character
  138. constant, which is one character  enclosed  in  single
  139. quotes.   However,  it  may  be  any quantity that fits in a
  140. byte, as in flags below:
  141.  
  142.      char quest, newline, flags;
  143.      quest = '?';
  144.      newline = '\n';
  145.      flags = 077;
  146.  
  147.      The sequence `\n' is C notation for  ``newline  charac-
  148. ter'', which, when printed, skips the terminal to the begin-
  149. ning of the next line.  Notice that `\n' represents  only  a
  150. single  character.  There are several other ``escapes'' like
  151. `\n'  for representing hard-to-get or invisible  characters,
  152. such  as  `\t'  for tab, `\b' for backspace, `\0' for end of
  153. file, and `\\' for the backslash itself.
  154.  
  155.      float and double constants are discussed in section 26.
  156.  
  157. 5. Simple I/O _ getchar, putchar, printf
  158.  
  159.  
  160.      main( ) {
  161.              char c;
  162.              c = getchar( );
  163.              putchar(c);
  164.      }
  165.  
  166.  
  167.      getchar and putchar are the basic I/O library functions
  168. in C.  getchar fetches one character from the standard input
  169. (usually the terminal) each time it is called,  and  returns
  170. that  character  as  the  value  of  the  function.  When it
  171. reaches the end of whatever file it is  reading,  thereafter
  172. it  returns  the  character  represented by `\0' (ascii NUL,
  173. which has value zero).  We will see how  to  use  this  very
  174. shortly.
  175.  
  176.      putchar puts one character out on the  standard  output
  177. (usually  the terminal) each time it is called.  So the pro-
  178. gram above reads one character and writes it back  out.   By
  179. itself,  this isn't very interesting, but observe that if we
  180. put a loop around this, and add a test for end of  file,  we
  181. have a complete program for copying one file to another.
  182.  
  183.      printf is a more  complicated  function  for  producing
  184. formatted  output.  We will talk about only the simplest use
  185. of it.  Basically, printf uses its first argument as format-
  186. ting  information, and any successive arguments as variables
  187. to be output.  Thus
  188.  
  189.      printf ("hello, world\n");
  190.  
  191. is the simplest use  _  the  string  ``hello,  world\n''  is
  192. printed  out.   No  formatting information, no variables, so
  193. the string is dumped out verbatim.  The newline is necessary
  194. to put this out on a line by itself.  (The construction
  195.  
  196.      "hello, world\n"
  197.  
  198. is really an array of chars.  More about this shortly.)
  199.  
  200.      More complicated, if sum is 6,
  201.  
  202.      printf ("sum is %d\n", sum);
  203.  
  204. prints
  205.  
  206.      sum is 6
  207.  
  208. Within the first argument of printf, the  characters  ``%d''
  209. signify that the next argument in the argument list is to be
  210. printed as a base 10 number.
  211.  
  212.      Other useful formatting commands are  ``%c''  to  print
  213. out  a  single  character,  ``%s''  to  print  out an entire
  214. string, and ``%o'' to print a number  as  octal  instead  of
  215. decimal (no leading zero).  For example,
  216.  
  217.      n = 511;
  218.      printf ("What is the value of %d in octal?", n);
  219.      printf ("  %s! %d decimal is %o octal\n", "Right", n, n);
  220.  
  221. prints
  222.  
  223.      What is the value of 511 in octal?  Right! 511  decimal
  224.      is 777 octal
  225.  
  226. Notice that there is no newline at the end of the first out-
  227. put  line.   Successive calls to printf (and/or putchar, for
  228. that matter) simply put out  characters.   No  newlines  are
  229. printed unless you ask for them.  Similarly, on input, char-
  230. acters are read one at a time as you  ask  for  them.   Each
  231. line is generally terminated by a newline (\n), but there is
  232. otherwise no concept of record.
  233.  
  234. 6. If; relational operators; compound statements
  235.  
  236.      The basic conditional-testing statement in C is the  if
  237. statement:
  238.  
  239.      c = getchar( );
  240.      if( c == '?' )
  241.              printf("why did you type a question mark?\n");
  242.  
  243. The simplest form of if is
  244.  
  245.      if (expression) statement
  246.  
  247.  
  248.      The condition to be tested is any  expression  enclosed
  249. in parentheses.  It is followed by a statement.  The expres-
  250. sion is evaluated, and if its value is non-zero, the  state-
  251. ment  is  executed.   There's an optional else clause, to be
  252. described soon.
  253.  
  254.      The character sequence `=='  is one of  the  relational
  255. operators in C; here is the complete set:
  256.  
  257.      ==      equal to (.EQ. to Fortraners)
  258.      !=      not equal to
  259.      >       greater than
  260.      <       less than
  261.      >=      greater than or equal to
  262.      <=      less than or equal to
  263.  
  264.  
  265.      The value of ``expression relation expression'' is 1 if
  266. the relation is true, and 0 if false.  Don't forget that the
  267. equality test is `=='; a single `='  causes  an  assignment,
  268. not a test, and invariably leads to disaster.
  269.  
  270.      Tests can be combined with the  operators  `&&'  (AND),
  271. `||'  (OR), and `!' (NOT).  For example, we can test whether
  272. a character is blank or tab or newline with
  273.  
  274.      if( c==' ' || c=='\t' || c=='\n' ) ...
  275.  
  276. C guarantees that `&&' and `||' are evaluated left to  right
  277. _ we shall soon see cases where this matters.
  278.  
  279.      One of the nice things about C is  that  the  statement
  280. part of an if can be made arbitrarily complicated by enclos-
  281. ing a set of statements in {}.  As a simple example, suppose
  282. we want to ensure that a is bigger than b, as part of a sort
  283. routine.  The interchange of a and b takes three  statements
  284. in C, grouped together by {}:
  285.  
  286.      if (a < b) {
  287.              t = a;
  288.              a = b;
  289.              b = t;
  290.      }
  291.  
  292.  
  293.      As a general rule in C, anywhere you can use  a  simple
  294. statement, you can use any compound statement, which is just
  295. a number of simple or compound ones enclosed in  {}.   There
  296. is  no  semicolon  after  the } of a compound statement, but
  297. there _i_s a semicolon after the last  non-compound  statement
  298. inside the {}.
  299.  
  300.      The ability to replace  single  statements  by  complex
  301. ones  at will is one feature that makes C much more pleasant
  302. to use than Fortran.  Logic (like the exchange in the previ-
  303. ous  example)  which would require several GOTO's and labels
  304. in Fortran can and should be done in C  without  any,  using
  305. compound statements.
  306.  
  307. 7. While Statement; Assignment within  an  Expression; Null
  308. Statement
  309.  
  310.      The basic looping mechanism in C is  the  while  state-
  311. ment.   Here's a program that copies its input to its output
  312. a character at a time.  Remember that `\0' marks the end  of
  313. file.
  314.  
  315.      main( ) {
  316.              char c;
  317.              while( (c=getchar( )) != '\0' )
  318.                      putchar(c);
  319.      }
  320.  
  321. The while statement is a loop, whose general form is
  322.  
  323.      while (expression) statement
  324.  
  325. Its meaning is
  326.  
  327.      (a) evaluate the expression
  328.      (b) if its value is true (i.e., not zero)
  329.                      do the statement, and go back to (a)
  330.  
  331. Because the expression is tested  before  the  statement  is
  332. executed,  the  statement  part  can be executed zero times,
  333. which is often desirable.   As  in  the  if  statement,  the
  334. expression and the statement can both be arbitrarily compli-
  335. cated, although we haven't seen that yet.  Our example  gets
  336. the  character,  assigns  it  to c, and then tests if it's a
  337. `\0''.  If it is not a `\0', the statement part of the while
  338. is   executed,  printing  the  character.   The  while  then
  339. repeats.  When the input character is finally  a  `\0',  the
  340. while terminates, and so does main.
  341.  
  342.      Notice that we used an assignment statement
  343.  
  344.      c = getchar( )
  345.  
  346. within an expression.  This is a handy  notational  shortcut
  347. which often produces clearer code.  (In fact it is often the
  348. only way to write the code cleanly.   As  an  exercise,  re-
  349. write  the  file-copy  without using an assignment inside an
  350. expression.) It works because an assignment statement has  a
  351. value,  just as any other expression does.  Its value is the
  352. value of the right hand side.  This also implies that we can
  353. use multiple assignments like
  354.  
  355.      x = y = z = 0;
  356.  
  357. Evaluation goes from right to left.
  358.  
  359.      By the way, the extra  parentheses  in  the  assignment
  360. statement  within  the conditional were really necessary: if
  361. we had said
  362.  
  363.      c = getchar( ) != '\0'
  364.  
  365. c would be set to 0 or 1 depending on whether the  character
  366. fetched  was  an end of file or not.  This is because in the
  367. absence  of  parentheses  the  assignment  operator  `='  is
  368. evaluated  after  the  relational  operator  `!='.   When in
  369. doubt, or even if not, parenthesize.
  370.  
  371.      Since putchar(c) returns c as its  function  value,  we
  372. could also copy the input to the output by nesting the calls
  373. to getchar and putchar:
  374.  
  375.      main( ) {
  376.              while( putchar(getchar( )) != '\0' ) ;
  377.      }
  378.  
  379. What statement is being repeated?  None, or technically, the
  380. null  statement,  because all the work is really done within
  381. the test part of the while.  This version is  slightly  dif-
  382. ferent  from  the  previous  one,  because the final `\0' is
  383. copied to the output before we decide to stop.
  384.  
  385. 8. Arithmetic
  386.  
  387.      The arithmetic operators are the usual `+',  `-',  `*',
  388. and  `/'  (truncating  integer  division if the operands are
  389. both int), and the remainder or mod operator `%':
  390.  
  391.      x = a%b;
  392.  
  393. sets x to the remainder after a is divided by b (i.e., a mod
  394. b).   The  results  are machine dependent unless a and b are
  395. both positive.
  396.  
  397.      In arithmetic, char variables can  usually  be  treated
  398. like  int  variables.   Arithmetic  on  characters  is quite
  399. legal, and often makes sense:
  400.  
  401.      c = c + 'A' - 'a';
  402.  
  403. converts a single lower case ascii character stored in c  to
  404. upper  case, making use of the fact that corresponding ascii
  405. letters are a fixed distance apart.  The rule governing this
  406. arithmetic is that all chars are converted to int before the
  407. arithmetic is done.   Beware  that  conversion  may  involve
  408. sign-extension  _  if  the leftmost bit of a character is 1,
  409. the resulting integer might be negative.  (This doesn't hap-
  410. pen with genuine characters on any current machine.)
  411.  
  412.      So to convert a file into lower case:
  413.  
  414.      main( ) {
  415.              char c;
  416.              while( (c=getchar( )) != '\0' )
  417.                      if( 'A'<=c && c<='Z' )
  418.                              putchar(c+'a'-'A');
  419.                      else
  420.                              putchar(c);
  421.      }
  422.  
  423. Characters  have  different  sizes  on  different  machines.
  424. Further, this code won't work on an IBM machine, because the
  425. letters in the ebcdic alphabet are not contiguous.
  426.  
  427. 9. Else Clause; Conditional Expressions
  428.  
  429.      We just used an else after an  if.   The  most  general
  430. form of if is
  431.  
  432.      if (expression) statement1 else statement2
  433.  
  434. the else part is optional, but often useful.  The  canonical
  435. example sets x to the minimum of a and b:
  436.  
  437.      if (a < b)
  438.              x = a;
  439.      else
  440.              x = b;
  441.  
  442. Observe that there's a semicolon after x=a.
  443.  
  444.      C provides an alternate form of  conditional  which  is
  445. often  more concise.  It is called the ``conditional expres-
  446. sion'' because it is a  conditional  which  actually  has  a
  447. value and can be used anywhere an expression can.  The value
  448. of
  449.  
  450.      a<b ? a : b;
  451.  
  452. is a if a is less than b; it is b  otherwise.   In  general,
  453. the form
  454.  
  455.      expr1 ? expr2 : expr3
  456.  
  457. means ``evaluate expr1.  If it is not zero, the value of the
  458. whole thing is expr2; otherwise the value is expr3.''
  459.  
  460.      To set x to the minimum of a and b, then:
  461.  
  462.      x = (a<b ? a : b);
  463.  
  464. The parentheses aren't necessary because `?:'  is  evaluated
  465. before `=', but safety first.
  466.  
  467.      Going a step further, we could write the  loop  in  the
  468. lower-case program as
  469.  
  470.      while( (c=getchar( )) != '\0' )
  471.              putchar( ('A'<=c && c<='Z') ? c-'A'+'a' : c );
  472.  
  473.  
  474.      If's and else's can be used  to  construct  logic  that
  475. branches one of several ways and then rejoins, a common pro-
  476. gramming structure, in this way:
  477.  
  478.      if(...)
  479.              {...}
  480.      else if(...)
  481.              {...}
  482.      else if(...)
  483.              {...}
  484.      else
  485.              {...}
  486.  
  487. The conditions are tested in order, and exactly one block is
  488. executed  _  either  the first one whose if is satisfied, or
  489. the one for the last else.  When this block is finished, the
  490. next  statement executed is the one after the last else.  If
  491. no action is to be taken for the ``default'' case, omit  the
  492. last else.
  493.  
  494.      For example, to count letters, digits and others  in  a
  495. file, we could write
  496.  
  497.      main( ) {
  498.              int let, dig, other, c;
  499.              let = dig = other = 0;
  500.              while( (c=getchar( )) != '\0' )
  501.                      if( ('A'<=c && c<='Z') || ('a'<=c && c<='z') )  ++let;
  502.                      else if( '0'<=c && c<='9' )  ++dig;
  503.                      else  ++other;
  504.              printf("%d letters, %d digits, %d others\n", let, dig, other);
  505.      }
  506.  
  507. The `++' operator means ``increment by 1''; we will  get  to
  508. it in the next section.
  509.  
  510. 10. Increment and Decrement Operators
  511.  
  512.      In addition to the usual `-',  C  also  has  two  other
  513. interesting  unary  operators,  `++'  (increment)  and  `--'
  514. (decrement).  Suppose we want to count the lines in a file.
  515.  
  516.      main( ) {
  517.              int c,n;
  518.              n = 0;
  519.              while( (c=getchar( )) != '\0' )
  520.                      if( c == '\n' )
  521.                              ++n;
  522.              printf("%d lines\n", n);
  523.      }
  524.  
  525. ++n is equivalent to n=n+1 but clearer, particularly when  n
  526. is  a  complicated expression.  `++' and `--' can be applied
  527. only to int's and char's (and pointers which we haven't  got
  528. to yet).
  529.  
  530.      The unusual feature of `++' and `--' is that  they  can
  531. be used either before or after a variable.  The value of ++k
  532. is the value of k AFTER it has been incremented.  The  value
  533. of k++ is k BEFORE it is incremented.  Suppose k is 5.  Then
  534.  
  535.      x = ++k;
  536.  
  537. increments k to 6 and then sets x to  the  resulting  value,
  538. i.e., to 6.  But
  539.  
  540.      x = k++;
  541.  
  542. first sets x to to 5, and  THEN  increments  k  to  6.   The
  543. incrementing  effect  of  ++k and k++ is the same, but their
  544. values are respectively 5 and 6.  We shall soon see examples
  545. where both of these uses are important.
  546.  
  547. 11. Arrays
  548.  
  549.      In C, as in Fortran or PL/I, it  is  possible  to  make
  550. arrays  whose elements are basic types.  Thus we can make an
  551. array of 10 integers with the declaration
  552.  
  553.      int x[10];
  554.  
  555. The square brackets mean subscripting; parentheses are  used
  556. only  for function references.  Array indexes begin at zero,
  557. so the elements of x are
  558.  
  559.      x[0], x[1], x[2], ..., x[9]
  560.  
  561. If an array has n elements, the largest subscript is n-1.
  562.  
  563.      Multiple-dimension arrays are provided, though not much
  564. used  above  two  dimensions.   The declaration and use look
  565. like
  566.  
  567.      int name[10] [20];
  568.      n = name[i+j] [1] + name[k] [2];
  569.  
  570. Subscripts can be  arbitrary  integer  expressions.   Multi-
  571. dimension arrays are stored by row (opposite to Fortran), so
  572. the rightmost subscript varies fastest; name has 10 rows and
  573. 20 columns.
  574.  
  575.      Here is a program which reads a line, stores  it  in  a
  576. buffer,  and prints its length (excluding the newline at the
  577. end).
  578.  
  579.      main( ) {
  580.              int n, c;
  581.              char line[100];
  582.              n = 0;
  583.              while( (c=getchar( )) != '\n' ) {
  584.                      if( n < 100 )
  585.                              line[n] = c;
  586.                      n++;
  587.              }
  588.              printf("length = %d\n", n);
  589.      }
  590.  
  591.  
  592.      As a more complicated problem, suppose we want to print
  593. the  count  for  each  line  in the input, still storing the
  594. first 100 characters of each line.  Try it  as  an  exercise
  595. before looking at the solution:
  596.  
  597.      main( ) {
  598.              int n, c; char line[100];
  599.              n = 0;
  600.              while( (c=getchar( )) != '\0' )
  601.                      if( c == '\n' ) {
  602.                              printf("%d0, n);
  603.                              n = 0;
  604.                      }
  605.                      else {
  606.                              if( n < 100 ) line[n] = c;
  607.                              n++;
  608.                      }
  609.      }
  610.  
  611.  
  612. 12. Character Arrays; Strings
  613.  
  614.      Text is usually kept as an array of characters,  as  we
  615. did  with line[ ] in the example above.  By convention in C,
  616. the last character in a character array  should  be  a  `\0'
  617. because  most  programs  that  manipulate  character  arrays
  618. expect it.  For example, printf uses the `\0' to detect  the
  619. end of a character array when printing it out with a `%s'.
  620.  
  621.      We can copy a character array s  into  another  t  like
  622. this:
  623.  
  624.              i = 0;
  625.              while( (t[i]=s[i]) != '\0' )
  626.                      i++;
  627.  
  628.  
  629.      Most of the time we have to put in our own `\0' at  the
  630. end  of  a string; if we want to print the line with printf,
  631. it's necessary.  This code prints the character count before
  632. the line:
  633.  
  634.      main( ) {
  635.              int n;
  636.              char line[100];
  637.              n = 0;
  638.              while( (line[n++]=getchar( )) != '\n' );
  639.              line[n] = '\0';
  640.              printf("%d:\t%s", n, line);
  641.      }
  642.  
  643. Here we increment n in the subscript itself, but only  after
  644. the  previous  value  has been used.  The character is read,
  645. placed in line[n], and only then n is incremented.
  646.  
  647.      There is one place and one place only where C  puts  in
  648. the  `\0'  at the end of a character array for you, and that
  649. is in the construction
  650.  
  651.      "stuff between double quotes"
  652.  
  653. The compiler puts a `\0' at  the  end  automatically.   Text
  654. enclosed in double quotes is called a _s_t_r_i_n_g; its properties
  655. are precisely those of an (initialized) array of characters.
  656.  
  657. 13. For Statement
  658.  
  659.      The for statement is a somewhat generalized while  that
  660. lets us put the initialization and increment parts of a loop
  661. into a single statement along with the  test.   The  general
  662. form of the for is
  663.  
  664.      for( initialization; expression; increment )
  665.              statement
  666.  
  667. The meaning is exactly
  668.  
  669.              initialization;
  670.              while( expression ) {
  671.                      statement
  672.                      increment;
  673.              }
  674.  
  675. Thus, the following code does the same  array  copy  as  the
  676. example in the previous section:
  677.  
  678.              for( i=0; (t[i]=s[i]) != '\0'; i++ );
  679.  
  680. This slightly more ornate example adds up the elements of an
  681. array:
  682.  
  683.              sum = 0;
  684.              for( i=0; i<n; i++)
  685.                      sum = sum + array[i];
  686.  
  687.  
  688.      In the for statement, the initialization  can  be  left
  689. out  if  you  want,  but the semicolon has to be there.  The
  690. increment is also optional.  It is NOT followed by  a  semi-
  691. colon.   The  second clause, the test, works the same way as
  692. in the while: if  the  expression  is  true  (not  zero)  do
  693. another  loop, otherwise get on with the next statement.  As
  694. with the while, the for loop may be done zero times.  If the
  695. expression is left out, it is taken to be always true, so
  696.  
  697.      for( ; ; ) ...
  698.  
  699. and
  700.  
  701.      while( 1 ) ...
  702.  
  703. are both infinite loops.
  704.  
  705.      You might ask why we use a for since it's so much  like
  706. a while.  (You might also ask why we use a while because...)
  707. The for is usually preferable  because  it  keeps  the  code
  708. where  it's  used and sometimes eliminates the need for com-
  709. pound  statements,  as  in  this  code  that  zeros  a  two-
  710. dimensional array:
  711.  
  712.      for( i=0; i<n; i++ )
  713.              for( j=0; j<m; j++ )
  714.                      array[i][j] = 0;
  715.  
  716.  
  717. 14. Functions; Comments
  718.  
  719.      Suppose we want, as part of a larger program, to  count
  720. the  occurrences of the ascii characters in some input text.
  721. Let us also map illegal characters (those with value>127  or
  722. <0)  into  one  pile.   Since this is presumably an isolated
  723. part of the program, good  practice  dictates  making  it  a
  724. separate function.  Here is one way:
  725.  
  726.      main( ) {
  727.              int hist[129];          /* 128 legal chars + 1 illegal group */
  728.              ...
  729.              count(hist, 128);       /* count the letters into hist */
  730.              printf( ... );          /* comments look like this; use them */
  731.              ...             /* anywhere blanks, tabs or newlines could appear */
  732.      }
  733.  
  734.      count(buf, size)
  735.         int size, buf[ ]; {
  736.              int i, c;
  737.              for( i=0; i<=size; i++ )
  738.                      buf[i] = 0;                     /* set buf to zero */
  739.              while( (c=getchar( )) != '\0' ) {       /* read til eof */
  740.                      if( c > size || c < 0 )
  741.                              c = size;               /* fix illegal input */
  742.                      buf[c]++;
  743.              }
  744.              return;
  745.      }
  746.  
  747. We have already seen many examples of calling a function, so
  748. let  us  concentrate  on how to define one.  Since count has
  749. two arguments, we need to declare  them,  as  shown,  giving
  750. their  types, and in the case of buf, the fact that it is an
  751. array.  The declarations of arguments go between  the  argu-
  752. ment  list and the opening `{'.  There is no need to specify
  753. the size of the array buf, for  it  is  defined  outside  of
  754. count.
  755.  
  756.      The return statement simply says to go back to the cal-
  757. ling  routine.   In  fact, we could have omitted it, since a
  758. return is implied at the end of a function.
  759.  
  760.      What if we wanted count to  return  a  value,  say  the
  761. number  of characters read?  The return statement allows for
  762. this too:
  763.  
  764.              int i, c, nchar;
  765.              nchar = 0;
  766.              ...
  767.              while( (c=getchar( )) != '\0' ) {
  768.                      if( c > size || c < 0 )
  769.                              c = size;
  770.                      buf[c]++;
  771.                      nchar++;
  772.              }
  773.              return(nchar);
  774.  
  775. Any expression can appear within the parentheses.  Here is a
  776. function to compute the minimum of two integers:
  777.  
  778.      min(a, b)
  779.         int a, b; {
  780.              return( a < b ? a : b );
  781.      }
  782.  
  783.  
  784.  
  785.      To copy a character array, we could write the function
  786.  
  787.      strcopy(s1, s2)         /* copies s1 to s2 */
  788.         char s1[ ], s2[ ]; {
  789.              int i;
  790.              for( i = 0; (s2[i] = s1[i]) != '\0'; i++ );
  791.      }
  792.  
  793. As is often the case, all the work is done by the assignment
  794. statement  embedded in the test part of the for.  Again, the
  795. declarations of the arguments s1  and  s2  omit  the  sizes,
  796. because  they  don't  matter to strcopy.  (In the section on
  797. pointers, we will see a more efficient way to  do  a  string
  798. copy.)
  799.  
  800.      There is a subtlety in function usage  which  can  trap
  801. the  unsuspecting Fortran programmer.  Simple variables (not
  802. arrays) are passed in C by ``call by  value'',  which  means
  803. that  the  called function is given a copy of its arguments,
  804. and doesn't know their addresses.  This makes it  impossible
  805. to change the value of one of the actual input arguments.
  806.  
  807.      There are two ways out of this dilemma.  One is to make
  808. special  arrangements to pass to the function the address of
  809. a variable instead of its value.  The other is to  make  the
  810. variable  a  global  or external variable, which is known to
  811. each function by its name.  We will discuss both  possibili-
  812. ties in the next few sections.
  813.  
  814. 15. Local and External Variables
  815.  
  816.      If we say
  817.  
  818.      f( ) {
  819.              int x;
  820.              ...
  821.      }
  822.      g( ) {
  823.              int x;
  824.              ...
  825.      }
  826.  
  827. each x is LOCAL to its own routine _ the x in f is unrelated
  828. to   the   x   in  g.   (Local  variables  are  also  called
  829. ``automatic''.) Furthermore each local variable in a routine
  830. appears  only  when  the  function is called, and _d_i_s_a_p_p_e_a_r_s
  831. when the function is exited.  Local variables have no memory
  832. from one call to the next and must be explicitly initialized
  833. upon each entry.  (There is a static storage class for  mak-
  834. ing local variables with memory; we won't discuss it.)
  835.  
  836.      As opposed to local variables, external  variables  are
  837. defined  external  to  all  functions, and are (potentially)
  838. available to all functions.  External storage always remains
  839. in  existence.  To make variables external we have to define
  840. them external to all functions, and, wherever we want to use
  841. them, make a declaration.
  842.  
  843.      main( ) {
  844.              extern int nchar, hist[ ];
  845.              ...
  846.              count( );
  847.              ...
  848.      }
  849.  
  850.      count( ) {
  851.              extern int nchar, hist[ ];
  852.              int i, c;
  853.              ...
  854.      }
  855.  
  856.      int     hist[129];      /* space for histogram */
  857.      int     nchar;          /* character count */
  858.  
  859. Roughly speaking, any function  that  wishes  to  access  an
  860. external variable must contain an extern declaration for it.
  861. The declaration is the same as others, except for the  added
  862. keyword  extern.   Furthermore,  there  must  somewhere be a
  863. definition of the external variables external to  all  func-
  864. tions.
  865.  
  866.      External variables can be initialized; they are set  to
  867. zero  if  not explicitly initialized.  In its simplest form,
  868. initialization is done by putting the value (which must be a
  869. constant) after the definition:
  870.  
  871.      int     nchar   0;
  872.      char    flag    'f';
  873.        etc.
  874.  
  875. This is discussed further in a later section.
  876.  
  877.  
  878.      This ends our discussion of what might  be  called  the
  879. central  core of C.  You now have enough to write quite sub-
  880. stantial C programs, and it would probably be a good idea if
  881. you  paused long enough to do so.  The rest of this tutorial
  882. will describe some more ornate constructions, useful but not
  883. essential.
  884.  
  885. 16. Pointers
  886.  
  887.      A pointer in C is the address of something.   It  is  a
  888. rare  case  indeed  when  we  care what the specific address
  889. itself is, but pointers are a quite common way to get at the
  890. contents  of  something.   The unary operator `&' is used to
  891. produce the address of an object, if it has one. Thus
  892.  
  893.              int a, b;
  894.              b = &a;
  895.  
  896. puts the address of a into b.  We  can't  do  much  with  it
  897. except print it or pass it to some other routine, because we
  898. haven't given b the right kind of declaration.   But  if  we
  899. declare  that  b is indeed a pointer to an integer, we're in
  900. good shape:
  901.  
  902.              int a, *b, c;
  903.              b = &a;
  904.              c = *b;
  905.  
  906. b contains the address of a and `c = *b' means  to  use  the
  907. value in b as an address, i.e., as a pointer.  The effect is
  908. that  we  get  back  the  contents  of  a,   albeit   rather
  909. indirectly.  (It's always the case that `*&x' is the same as
  910. x if x has an address.)
  911.  
  912.      The most frequent use of pointers in C is  for  walking
  913. efficiently along arrays.  In fact, in the implementation of
  914. an array, the array  name  represents  the  address  of  the
  915. zeroth element of the array, so you can't use it on the left
  916. side of an expression.  (You can't  change  the  address  of
  917. something by assigning to it.) If we say
  918.  
  919.      char *y;
  920.      char x[100];
  921.  
  922. y is of type pointer to character (although it  doesn't  yet
  923. point  anywhere).  We can make y point to an element of x by
  924. either of
  925.  
  926.      y = &x[0];
  927.      y = x;
  928.  
  929. Since x is the address of x[0] this is legal and consistent.
  930.  
  931.      Now `*y' gives x[0].  More importantly,
  932.  
  933.      *(y+1)  gives x[1]
  934.      *(y+i)  gives x[i]
  935.  
  936. and the sequence
  937.  
  938.              y = &x[0];
  939.              y++;
  940.  
  941. leaves y pointing at x[1].
  942.  
  943.      Let's use pointers in a function length  that  computes
  944. how  long a character array is.  Remember that by convention
  945. all character arrays are terminated with a  `\0'.   (And  if
  946. they  aren't, this program will blow up inevitably.) The old
  947. way:
  948.  
  949.      length(s)
  950.         char s[ ]; {
  951.              int n;
  952.              for( n=0; s[n] != '\0'; )
  953.                      n++;
  954.              return(n);
  955.      }
  956.  
  957. Rewriting with pointers gives
  958.  
  959.      length(s)
  960.         char *s; {
  961.              int n;
  962.              for( n=0; *s != '\0'; s++ )
  963.                      n++;
  964.              return(n);
  965.      }
  966.  
  967. You can now see why we have to say  what  kind  of  thing  s
  968. points  to  _  if  we're to increment it with s++ we have to
  969. increment it by the right amount.
  970.  
  971.      The pointer version is more efficient (this  is  almost
  972. always true) but even more compact is
  973.  
  974.              for( n=0; *s++ != '\0'; n++ );
  975.  
  976. The `*s'  returns  a  character;  the  `++'  increments  the
  977. pointer  so  we'll  get the next character next time around.
  978. As you can see, as we make things more  efficient,  we  also
  979. make them less clear.  But `*s++' is an idiom so common that
  980. you have to know it.
  981.  
  982.      Going a step further, here's our function strcopy  that
  983. copies a character array s to another t.
  984.  
  985.      strcopy(s,t)
  986.         char *s, *t; {
  987.              while(*t++ = *s++);
  988.      }
  989.  
  990. We have omitted the  test  against  `\0',  because  `\0'  is
  991. identically  zero;  you  will  often  see the code this way.
  992. (You MUST have a space after the `=': see section 25.)
  993.  
  994.      For arguments  to  a  function,  and  there  only,  the
  995. declarations
  996.  
  997.      char s[ ];
  998.      char *s;
  999.  
  1000. are equivalent _ a  pointer  to  a  type,  or  an  array  of
  1001. unspecified size of that type, are the same thing.
  1002.  
  1003.      If this all seems mysterious, copy  these  forms  until
  1004. they  become  second  nature.  You don't often need anything
  1005. more complicated.
  1006.  
  1007. 17. Function Arguments
  1008.  
  1009.      Look back at the function strcopy in the previous  sec-
  1010. tion.  We passed it two string names as arguments, then pro-
  1011. ceeded to clobber both of them by  incrementation.   So  how
  1012. come we don't lose the original strings in the function that
  1013. called strcopy?
  1014.  
  1015.      As we said before, C is a ``call by  value''  language:
  1016. when  you  make a function call like f(x), the VALUE of x is
  1017. passed, not its address.  So there's no way to ALTER x  from
  1018. inside  f.  If x is an array (char x[10]) this isn't a prob-
  1019. lem, because x IS an address anyway, and you're  not  trying
  1020. to  change  it, just what it addresses.  This is why strcopy
  1021. works as it does.  And it's convenient not to have to  worry
  1022. about making temporary copies of the input arguments.
  1023.  
  1024.      But what if x is a scalar and you do want to change it?
  1025. In  that  case,  you have to pass the ADDRESS of x to f, and
  1026. then use it as a pointer.  Thus for example, to  interchange
  1027. two integers, we must write
  1028.  
  1029.      flip(x, y)
  1030.         int *x, *y; {
  1031.              int temp;
  1032.              temp = *x;
  1033.              *x = *y;
  1034.              *y = temp;
  1035.      }
  1036.  
  1037. and to call flip, we have to pass the addresses of the vari-
  1038. ables:
  1039.  
  1040.      flip (&a, &b);
  1041.  
  1042.  
  1043. 18. Multiple Levels of Pointers; Program Arguments
  1044.  
  1045.      When a C program is called, the arguments on  the  com-
  1046. mand line are made available to the main program as an argu-
  1047. ment count argc and an array of character strings argv  con-
  1048. taining  the arguments.  Manipulating these arguments is one
  1049. of the most common  uses  of  multiple  levels  of  pointers
  1050. (``pointer  to  pointer  to  ...'').  By convention, argc is
  1051. greater than zero; the first argument (in  argv[0])  is  the
  1052. command name itself.
  1053.  
  1054.      Here is a program that simply echoes its arguments.
  1055.  
  1056.      main(argc, argv)
  1057.         int argc;
  1058.         char **argv; {
  1059.              int i;
  1060.              for( i=1; i < argc; i++ )
  1061.      }
  1062.  
  1063. Step by step: main is called with two arguments,  the  argu-
  1064. ment count and the array of arguments.  argv is a pointer to
  1065. an array, whose individual elements are pointers  to  arrays
  1066. of  characters.  The zeroth argument is the name of the com-
  1067. mand itself, so we start to print with the  first  argument,
  1068. until  we've  printed them all.  Each argv[i] is a character
  1069. array, so we use a `%s' in the printf.
  1070.  
  1071.      You will sometimes see the declaration of argv  written
  1072. as
  1073.  
  1074.      char *argv[ ];
  1075.  
  1076. which is equivalent.  But we can't  use  char  argv[  ][  ],
  1077. because  both  dimensions are variable and there would be no
  1078. way to figure out how big the array is.
  1079.  
  1080.      Here's a bigger example using argc and argv.  A  common
  1081. convention  in  C  programs is that if the first argument is
  1082. `-', it indicates a flag of some sort.  For example, suppose
  1083. we want a program to be callable as
  1084.  
  1085.      prog -abc arg1 arg2 ...
  1086.  
  1087. where the `-' argument is optional; if it is present, it may
  1088. be followed by any combination of a, b, and c.
  1089.  
  1090.      main(argc, argv)
  1091.         int argc;
  1092.         char **argv; {
  1093.              ...
  1094.              aflag = bflag = cflag  = 0;
  1095.              if( argc > 1 && argv[1][0] == '-' ) {
  1096.                      for( i=1; (c=argv[1][i]) != '\0'; i++ )
  1097.                              if( c=='a' )
  1098.                                      aflag++;
  1099.                              else if( c=='b' )
  1100.                                      bflag++;
  1101.                              else if( c=='c' )
  1102.                                      cflag++;
  1103.                              else
  1104.                                      printf("%c?\n", c);
  1105.                      --argc;
  1106.                      ++argv;
  1107.              }
  1108.              ...
  1109.  
  1110.  
  1111.      There are several  things  worth  noticing  about  this
  1112. code.   First,  there  is  a real need for the left-to-right
  1113. evaluation that &&  provides;  we  don't  want  to  look  at
  1114. argv[1] unless we know it's there.  Second, the statements
  1115.  
  1116.              --argc;
  1117.              ++argv;
  1118.  
  1119. let us march along the argument list by one position, so  we
  1120. can skip over the flag argument as if it had never existed _
  1121. the rest of the program is independent  of  whether  or  not
  1122. there  was a flag argument.  This only works because argv is
  1123. a pointer which can be incremented.
  1124.  
  1125. 19. The Switch Statement; Break; Continue
  1126.  
  1127.      The switch statement can be used to replace the  multi-
  1128. way  test  we  used in the last example.  When the tests are
  1129. like this:
  1130.  
  1131.      if( c == 'a' ) ...
  1132.      else if( c == 'b' ) ...
  1133.      else if( c == 'c' ) ...
  1134.      else ...
  1135.  
  1136. testing a value against a series of  constants,  the  switch
  1137. statement  is  often  clearer and usually gives better code.
  1138. Use it like this:
  1139.  
  1140.      switch( c ) {
  1141.  
  1142.      case 'a':
  1143.              aflag++;
  1144.              break;
  1145.      case 'b':
  1146.              bflag++;
  1147.              break;
  1148.      case 'c':
  1149.              cflag++;
  1150.              break;
  1151.      default:
  1152.              printf("%c?\n", c);
  1153.              break;
  1154.      }
  1155.  
  1156. The case statements  label  the  various  actions  we  want;
  1157. default  gets done if none of the other cases are satisfied.
  1158. (A default is optional; if it isn't there, and none  of  the
  1159. cases match, you just fall out the bottom.)
  1160.  
  1161.      The break statement in this  example  is  new.   It  is
  1162. there  because  the  cases are just labels, and after you do
  1163. one of them, you fall through to the next  unless  you  take
  1164. some  explicit  action to escape.  This is a mixed blessing.
  1165. On the positive side, you can have multiple cases on a  sin-
  1166. gle  statement;  we might want to allow both upper and lower
  1167.      case 'a':  case 'A':    ...
  1168.  
  1169.      case 'b':  case 'B':    ...
  1170.       etc.
  1171.  
  1172. But what if we just want to get out after doing case  `a'  ?
  1173. We  could get out of a case of the switch with a label and a
  1174. goto, but this is really ugly.  The break statement lets  us
  1175. exit without either goto or label.
  1176.  
  1177.      switch( c ) {
  1178.  
  1179.      case 'a':
  1180.              aflag++;
  1181.              break;
  1182.      case 'b':
  1183.              bflag++;
  1184.              break;
  1185.       ...
  1186.      }
  1187.      /* the break statements get us here directly */
  1188.  
  1189. The break statement also works in for and while statements _
  1190. it causes an immediate exit from the loop.
  1191.  
  1192.      The continue statement  works  _o_n_l_y  inside  for's  and
  1193. while's;  it  causes  the  next  iteration of the loop to be
  1194. started.  This means it goes to the increment  part  of  the
  1195. for  and  the  test part of the while.  We could have used a
  1196. continue in our example to get on with the next iteration of
  1197. the for, but it seems clearer to use break instead.
  1198.  
  1199. 20. Structures
  1200.  
  1201.      The main use of structures is to lump together  collec-
  1202. tions  of disparate variable types, so they can conveniently
  1203. be treated as a unit.  For example, if  we  were  writing  a
  1204. compiler  or  assembler,  we  might need for each identifier
  1205. information like its name (a character  array),  its  source
  1206. line  number  (an integer), some type information (a charac-
  1207. ter, perhaps), and probably a usage count (another integer).
  1208.  
  1209.              char    id[10];
  1210.              int     line;
  1211.              char    type;
  1212.              int     usage;
  1213.  
  1214.  
  1215.      We can make a structure out of this quite  easily.   We
  1216. first  tell  C  what  the structure will look like, that is,
  1217. what kinds of things it contains; after that we can actually
  1218. reserve  storage  for  it,  either  in the same statement or
  1219. separately.  The simplest thing is to define it and allocate
  1220. storage all at once:
  1221.  
  1222.      struct {
  1223.              char    id[10];
  1224.              int     line;
  1225.              char    type;
  1226.              int     usage;
  1227.      } sym;
  1228.  
  1229.  
  1230.      This defines sym to be a structure with  the  specified
  1231. shape;  id,  line,  type and usage are members of the struc-
  1232. ture.  The way we refer to  any  particular  member  of  the
  1233. structure is
  1234.  
  1235.      structure-name . member
  1236.  
  1237. as in
  1238.  
  1239.              sym.type = 077;
  1240.              if( sym.usage == 0 ) ...
  1241.              while( sym.id[j++] ) ...
  1242.                 etc.
  1243.  
  1244. Although the names of structure members never  stand  alone,
  1245. they  still have to be unique _ there can't be another id or
  1246. usage in some other structure.
  1247.  
  1248.      So far we  haven't  gained  much.   The  advantages  of
  1249. structures  start to come when we have arrays of structures,
  1250. or when we want to pass  complicated  data  layouts  between
  1251. functions.   Suppose we wanted to make a symbol table for up
  1252. to 100 identifiers.  We could extend our definitions like
  1253.  
  1254.              char    id[100][10];
  1255.              int     line[100];
  1256.              char    type[100];
  1257.              int     usage[100];
  1258.  
  1259. but a structure lets us rearrange this  spread-out  informa-
  1260. tion  so  all the data about a single identifer is collected
  1261. into one lump:
  1262.  
  1263.      struct {
  1264.              char    id[10];
  1265.              int     line;
  1266.              char    type;
  1267.              int     usage;
  1268.      } sym[100];
  1269.  
  1270. This makes sym an array of structures;  each  array  element
  1271. has the specified shape.  Now we can refer to members as
  1272.  
  1273.              sym[i].usage++; /* increment usage of i-th identifier */
  1274.              for( j=0; sym[i].id[j++] != '\0'; ) ...
  1275.                 etc.
  1276.  
  1277. Thus to print a list of all identifiers  that  haven't  been
  1278. used, together with their line number,
  1279.  
  1280.              for( i=0; i<nsym; i++ )
  1281.                      if( sym[i].usage == 0 )
  1282.                              printf("%d\t%s\n", sym[i].line, sym[i].id);
  1283.  
  1284.  
  1285.      Suppose we now want to write  a  function  lookup(name)
  1286. which  will tell us if name already exists in sym, by giving
  1287. its index, or that it doesn't, by returning a -1.  We  can't
  1288. pass  a structure to a function directly _ we have to either
  1289. define it externally, or pass a pointer to  it.   Let's  try
  1290. the first way first.
  1291.  
  1292.      int     nsym    0;      /* current length of symbol table */
  1293.  
  1294.      struct {
  1295.              char    id[10];
  1296.              int     line;
  1297.              char    type;
  1298.              int     usage;
  1299.      } sym[100];             /* symbol table */
  1300.  
  1301.      main( ) {
  1302.              ...
  1303.              if( (index = lookup(newname)) >= 0 )
  1304.                      sym[index].usage++;             /* already there ... */
  1305.              else
  1306.                      install(newname, newline, newtype);
  1307.              ...
  1308.      }
  1309.  
  1310.      lookup(s)
  1311.         char *s; {
  1312.              int i;
  1313.              extern struct {
  1314.                      char    id[10];
  1315.                      int     line;
  1316.                      char    type;
  1317.                      int     usage;
  1318.              } sym[ ];
  1319.  
  1320.              for( i=0; i<nsym; i++ )
  1321.                      if( compar(s, sym[i].id) > 0 )
  1322.                              return(i);
  1323.              return(-1);
  1324.      }
  1325.  
  1326.      compar(s1,s2)           /*  return 1 if s1==s2, 0 otherwise */
  1327.         char *s1, *s2; {
  1328.              while( *s1++ == *s2 )
  1329.                      if( *s2++ == '\0' )
  1330.                              return(1);
  1331.              return(0);
  1332.      }
  1333.  
  1334. The declaration of the structure in lookup isn't  needed  if
  1335. the  external definition precedes its use in the same source
  1336. file, as we shall see in a moment.
  1337.  
  1338.      Now what if we want to use pointers?
  1339.  
  1340.      struct  symtag {
  1341.              char    id[10];
  1342.              int     line;
  1343.              char    type;
  1344.              int     usage;
  1345.      } sym[100], *psym;
  1346.  
  1347.              psym = &sym[0]; /* or p = sym; */
  1348.  
  1349. This makes psym a pointer to our kind of structure (the sym-
  1350. bol  table),  then initializes it to point to the first ele-
  1351. ment of sym.
  1352.  
  1353.      Notice that we added something after the word struct: a
  1354. ``tag''  called  symtag.   This puts a name on our structure
  1355. definition so we can refer to it later without repeating the
  1356. definition.   It's  not  necessary  but  useful.  In fact we
  1357. could have said
  1358.  
  1359.      struct  symtag {
  1360.              ... structure definition
  1361.      };
  1362.  
  1363. which wouldn't have assigned any storage at  all,  and  then
  1364. said
  1365.  
  1366.      struct  symtag  sym[100];
  1367.      struct  symtag  *psym;
  1368.  
  1369. which would define the array and the pointer.  This could be
  1370. condensed further, to
  1371.  
  1372.      struct  symtag  sym[100], *psym;
  1373.  
  1374.  
  1375.      The way we actually refer to an member of  a  structure
  1376. by a pointer is like this:
  1377.  
  1378.              ptr -> structure-member
  1379.  
  1380. The symbol `->' means  we're  pointing  at  a  member  of  a
  1381.  
  1382.  
  1383.  
  1384.  
  1385.  
  1386.  
  1387.  
  1388.  
  1389. C Tutorial                 - 27 -
  1390.  
  1391.  
  1392.  
  1393. structure;  `->'  is  only  used  in that context.  ptr is a
  1394. pointer to the (base  of)  a  structure  that  contains  the
  1395. structure   member.   The  expression  ptr->structure-member
  1396. refers to the indicated member of the pointed-to  structure.
  1397. Thus we have constructions like:
  1398.  
  1399.      psym->type = 1;
  1400.      psym->id[0] = 'a';
  1401.  
  1402. and so on.
  1403.  
  1404.      For more complicated pointer expressions, it's wise  to
  1405. use  parentheses  to  make it clear who goes with what.  For
  1406. example,
  1407.  
  1408.      struct { int x, *y; } *p;
  1409.      p->x++  increments x
  1410.      ++p->x  so does this!
  1411.      (++p)->x        increments p before getting x
  1412.      *p->y++ uses y as a pointer, then increments it
  1413.      *(p->y)++       so does this
  1414.      *(p++)->y       uses y as a pointer, then increments p
  1415.  
  1416. The way to remember these is that ->, . (dot), ( ) and  [  ]
  1417. bind  very tightly.  An expression involving one of these is
  1418. treated as a unit.  p->x,  a[i],  y.x  and  f(b)  are  names
  1419. exactly as abc is.
  1420.  
  1421.      If p is a pointer to a structure, any arithmetic  on  p
  1422. takes  into  account  the acutal size of the structure.  For
  1423. instance, p++ increments p by the correct amount to get  the
  1424. next  element  of the array of structures.  But don't assume
  1425. that the size of a structure is the sum of the sizes of  its
  1426. members  _ because of alignments of different sized objects,
  1427. there may be ``holes'' in a structure.
  1428.  
  1429.      Enough theory. Here is the lookup  example,  this  time
  1430. with pointers.
  1431.  
  1432.      struct symtag {
  1433.              char    id[10];
  1434.              int     line;
  1435.              char    type;
  1436.              int     usage;
  1437.      } sym[100];
  1438.  
  1439.      main( ) {
  1440.              struct symtag *lookup( );
  1441.              struct symtag *psym;
  1442.              ...
  1443.              if( (psym = lookup(newname)) )  /* non-zero pointer */
  1444.                      psym -> usage++;                /* means already there */
  1445.              else
  1446.                      install(newname, newline, newtype);
  1447.  
  1448.  
  1449.  
  1450.  
  1451.  
  1452.  
  1453.  
  1454.  
  1455. C Tutorial                 - 28 -
  1456.  
  1457.  
  1458.  
  1459.              ...
  1460.      }
  1461.  
  1462.      struct symtag *lookup(s)
  1463.         char *s; {
  1464.              struct symtag *p;
  1465.              for( p=sym; p < &sym[nsym]; p++ )
  1466.                      if( compar(s, p->id) > 0)
  1467.                              return(p);
  1468.              return(0);
  1469.      }
  1470.  
  1471. The function compar doesn't  change:  `p->id'  refers  to  a
  1472. string.
  1473.  
  1474.      In main we test the pointer returned by lookup  against
  1475. zero,  relying  on  the fact that a pointer is by definition
  1476. never zero when it really points at  something.   The  other
  1477. pointer manipulations are trivial.
  1478.  
  1479.      The only complexity is the set of lines like
  1480.  
  1481.      struct symtag *lookup( );
  1482.  
  1483. This brings us to an area that we will treat only  hurriedly
  1484. _  the question of function types.  So far, all of our func-
  1485. tions have returned integers (or characters, which are  much
  1486. the  same).   What  do we do when the function returns some-
  1487. thing else, like a pointer to a structure?  The rule is that
  1488. any  function  that  doesn't return an int has to say expli-
  1489. citly what it does return.  The type information goes before
  1490. the  function  name  (which  can make the name hard to see).
  1491. Examples:
  1492.  
  1493.      char f(a)
  1494.         int a; {
  1495.              ...
  1496.      }
  1497.  
  1498.      int *g( ) { ... }
  1499.  
  1500.      struct symtag *lookup(s) char *s; { ... }
  1501.  
  1502. The function f returns a character, g returns a  pointer  to
  1503. an integer, and lookup returns a pointer to a structure that
  1504. looks like symtag.  And if we're going to use one  of  these
  1505. functions, we have to make a declaration where we use it, as
  1506. we did in main above.
  1507.  
  1508.      Notice th parallelism between the declarations
  1509.  
  1510.              struct symtag *lookup( );
  1511.              struct symtag *psym;
  1512.  
  1513.  
  1514.  
  1515.  
  1516.  
  1517.  
  1518.  
  1519.  
  1520.  
  1521. C Tutorial                 - 29 -
  1522.  
  1523.  
  1524.  
  1525. In effect, this says that lookup( ) and psym are  both  used
  1526. the  same way _ as a pointer to a strcture _ even though one
  1527. is a variable and the other is a function.
  1528.  
  1529. 21. Initialization of Variables
  1530.  
  1531.      An external variable may be initialized at compile time
  1532. by  following its name with an initializing value when it is
  1533. defined.  The initializing value has to be  something  whose
  1534. value is known at compile time, like a constant.
  1535.  
  1536.      int     x       0;      /* "0" could be any constant */
  1537.      int     a       'a';
  1538.      char    flag    0177;
  1539.      int     *p      &y[1];  /* p now points to y[1] */
  1540.  
  1541. An external array can be initialized by following  its  name
  1542. with a list of initializations enclosed in braces:
  1543.  
  1544.      int     x[4]    {0,1,2,3};              /* makes x[i] = i */
  1545.      int     y[ ]    {0,1,2,3};              /* makes y big enough for 4 values */
  1546.      char    *msg    "syntax error\n";       /* braces unnecessary here */
  1547.      char *keyword[ ]{
  1548.              "if",
  1549.              "else",
  1550.              "for",
  1551.              "while",
  1552.              "break",
  1553.              "continue",
  1554.              0
  1555.      };
  1556.  
  1557. This last one is very useful _ it makes keyword an array  of
  1558. pointers  to character strings, with a zero at the end so we
  1559. can identify the last element easily.  A simple lookup  rou-
  1560. tine  could  scan  this  until  it  either  finds a match or
  1561. encounters a zero keyword pointer:
  1562.  
  1563.      lookup(str)             /* search for str in keyword[ ] */
  1564.         char *str; {
  1565.              int i,j,r;
  1566.              for( i=0; keyword[i] != 0; i++) {
  1567.                      for( j=0; (r=keyword[i][j]) == str[j] && r != '\0'; j++ );
  1568.                      if( r == str[j] )
  1569.                              return(i);
  1570.              }
  1571.              return(-1);
  1572.      }
  1573.  
  1574.  
  1575.      Sorry _ neither local variables nor structures  can  be
  1576. initialized.
  1577.  
  1578. 22. Scope Rules: Who Knows About What
  1579.  
  1580.      A complete C program need not be compiled all at  once;
  1581. the source text of the program may be kept in several files,
  1582. and  previously  compiled  routines  may  be   loaded   from
  1583. libraries.  How do we arrange that data gets passed from one
  1584. routine to another?  We have already seen how to  use  func-
  1585. tion  arguments  and  values,  so let us talk about external
  1586. data.  Warning: the words  declaration  and  definition  are
  1587. used precisely in this section; don't treat them as the same
  1588. thing.
  1589.  
  1590.      A major shortcut exists for making extern declarations.
  1591. If  the  definition  of a variable appears BEFORE its use in
  1592. some function, no extern declaration is  needed  within  the
  1593. function.  Thus, if a file contains
  1594.  
  1595.      f1( ) { ... }
  1596.  
  1597.      int foo;
  1598.  
  1599.      f2( ) { ... foo = 1; ... }
  1600.  
  1601.      f3( ) { ... if ( foo ) ... }
  1602.  
  1603. no declaration of foo is needed  in  either  f2  or  or  f3,
  1604. because  the external definition of foo appears before them.
  1605. But if f1 wants to use foo, it has to contain  the  declara-
  1606. tion
  1607.  
  1608.      f1( ) {
  1609.              extern int foo;
  1610.              ...
  1611.      }
  1612.  
  1613.  
  1614.      This is true  also  of  any  function  that  exists  on
  1615. another  file  _  if  it  wants  foo it has to use an extern
  1616. declaration for  it.   (If  somewhere  there  is  an  extern
  1617. declaration  for something, there must also eventually be an
  1618. external definition of it, or you'll get an ``undefined sym-
  1619. bol'' message.)
  1620.  
  1621.      There are some hidden pitfalls in external declarations
  1622. and  definitions if you use multiple source files.  To avoid
  1623. them, first, define and initialize  each  external  variable
  1624. only once in the entire set of files:
  1625.  
  1626.      int     foo     0;
  1627.  
  1628. You can get away with multiple external definitions on UNIX,
  1629. but  not  on  GCOS, so don't ask for trouble.  Multiple ini-
  1630. tializations are illegal everywhere.  Second, at the  begin-
  1631. ning  of any file that contains functions needing a variable
  1632. whose definition is in some other file,  put  in  an  extern
  1633. declaration, outside of any function:
  1634.  
  1635.      extern  int     foo;
  1636.  
  1637.      f1( ) { ... }
  1638.         etc.
  1639.  
  1640.  
  1641.      The #include compiler control  line,  to  be  discussed
  1642. shortly,  lets  you  make  a  single  copy  of  the external
  1643. declarations for a program and then stick them into each  of
  1644. the source files making up the program.
  1645.  
  1646. 23. #define, #include
  1647.  
  1648.      C provides a very limited macro facility.  You can say
  1649.  
  1650.      #define name            something
  1651.  
  1652. and thereafter anywhere ``name'' appears as a token, ``some-
  1653. thing'' will be substituted.  This is particularly useful in
  1654. parametering the sizes of arrays:
  1655.  
  1656.      #define ARRAYSIZE       100
  1657.              int     arr[ARRAYSIZE];
  1658.               ...
  1659.              while( i++ < ARRAYSIZE )...
  1660.  
  1661. (now we can alter the entire program by  changing  only  the
  1662. define) or in setting up mysterious constants:
  1663.  
  1664.      #define SET             01
  1665.      #define INTERRUPT       02      /* interrupt bit */
  1666.      #define ENABLED 04
  1667.       ...
  1668.      if( x & (SET | INTERRUPT | ENABLED) ) ...
  1669.  
  1670. Now we have meaningful  words  instead  of  mysterious  con-
  1671. stants.   (The  mysterious  operators `&' (AND) and `|' (OR)
  1672. will be covered in the  next  section.)  It's  an  excellent
  1673. practice  to  write  programs  without any literal constants
  1674. except in #define statements.
  1675.  
  1676.      There  are  several  warnings  about  #define.   First,
  1677. there's  no  semicolon at the end of a #define; all the text
  1678. from the name to the end of the line (except  for  comments)
  1679. is  taken  to  be the ``something''.  When it's put into the
  1680. text, blanks are placed around  it.   Good  style  typically
  1681. makes the name in the #define upper case _ this makes param-
  1682. eters more visible.  Definitions affect  things  only  after
  1683. they  occur,  and  only within the file in which they occur.
  1684. Defines can't be nested.  Last, if there is a #define  in  a
  1685. file, then the first character of the file MUST be a `#', to
  1686. signal the preprocessor that definitions exist.
  1687.  
  1688.  
  1689.      The other control word known  to  C  is  #include.   To
  1690. include one file in your source at compilation time, say
  1691.  
  1692.      #include "filename"
  1693.  
  1694. This is useful for putting a lot of heavily used data defin-
  1695. itions  and #define statements at the beginning of a file to
  1696. be compiled.  As with #define, the first line of a file con-
  1697. taining  a  #include  has to begin with a `#'.  And #include
  1698. can't be nested _ an included  file  can't  contain  another
  1699. #include.
  1700.  
  1701. 24. Bit Operators
  1702.  
  1703.      C has several  operators  for  logical  bit-operations.
  1704. For example,
  1705.  
  1706.      x = x & 0177;
  1707.  
  1708. forms the bit-wise AND of x and 0177, effectively  retaining
  1709. only the last seven bits of x.  Other operators are
  1710.  
  1711.      |       inclusive OR
  1712.      ^       (circumflex) exclusive OR
  1713.      ~       (tilde) 1's complement
  1714.      !       logical NOT
  1715.      <<      left shift (as in x<<2)
  1716.      >>      right shift     (arithmetic on PDP-11; logical on H6070, IBM360)
  1717.  
  1718.  
  1719. 25. Assignment Operators
  1720.  
  1721.      An unusual feature of  C  is  that  the  normal  binary
  1722. operators  like  `+',  `-',  etc.   can be combined with the
  1723. assignment operator `=' to form  new  assignment  operators.
  1724. For example,
  1725.  
  1726.      x =- 10;
  1727.  
  1728. uses the assignment operator `=-' to decrement x by 10, and
  1729.  
  1730.      x =& 0177
  1731.  
  1732. forms the AND of x and 0177.  This convention  is  a  useful
  1733. notational  shortcut,  particularly  if  x  is a complicated
  1734. expression.  The classic example is summing an array:
  1735.  
  1736.      for( sum=i=0; i<n; i++ )
  1737.              sum =+ array[i];
  1738.  
  1739. But the  spaces  around  the  operator  are  critical!   For
  1740.      x = -10;
  1741.  
  1742. sets x to -10, while
  1743.  
  1744.      x =- 10;
  1745.  
  1746. subtracts 10 from x.  When no space is present,
  1747.  
  1748.      x=-10;
  1749.  
  1750. also decreases x by 10.   This  is  quite  contrary  to  the
  1751. experience  of  most  programmers.  In particular, watch out
  1752. for things like
  1753.  
  1754.      c=*s++;
  1755.      y=&x[0];
  1756.  
  1757. both of which are almost  certainly  not  what  you  wanted.
  1758. Newer  versions of various compilers are courteous enough to
  1759. warn you about the ambiguity.
  1760.  
  1761.      Because  all  other  operators  in  an  expression  are
  1762. evaluated  before  the  assignment  operator,  the  order of
  1763. evaluation should be watched carefully:
  1764.  
  1765.      x = x<<y | z;
  1766.  
  1767. means ``shift x left y places, then OR with z, and store  in
  1768. x.'' But
  1769.  
  1770.      x =<< y | z;
  1771.  
  1772. means ``shift x left by y|z places'', which is  rather  dif-
  1773. ferent.
  1774.  
  1775. 26. Floating Point
  1776.  
  1777.      We've skipped over  floating  point  so  far,  and  the
  1778. treatment  here will be hasty.  C has single and double pre-
  1779. cision numbers (where the precision depends on  the  machine
  1780. at hand).  For example,
  1781.  
  1782.              double sum;
  1783.              float avg, y[10];
  1784.              sum = 0.0;
  1785.              for( i=0; i<n; i++ )
  1786.                      sum =+ y[i];
  1787.              avg = sum/n;
  1788.  
  1789. forms the sum and average of the array y.
  1790.  
  1791.      All floating arithmetic is done  in  double  precision.
  1792. Mixed mode arithmetic is legal; if an arithmetic operator in
  1793. an expression has both operands int or char, the  arithmetic
  1794. done  is  integer, but if one operand is int or char and the
  1795. other is float or double, both  operands  are  converted  to
  1796. double.  Thus if i and j are int and x is float,
  1797.  
  1798.      (x+i)/j         converts i and j to float
  1799.      x + i/j         does i/j integer, then converts
  1800.  
  1801. Type conversion may be made by assignment; for instance,
  1802.  
  1803.              int m, n;
  1804.              float x, y;
  1805.              m = x;
  1806.              y = n;
  1807.  
  1808. converts x to integer (truncating toward  zero),  and  n  to
  1809. floating point.
  1810.  
  1811.      Floating constants are just like those  in  Fortran  or
  1812. PL/I, except that the exponent letter is `e' instead of `E'.
  1813. Thus:
  1814.  
  1815.              pi = 3.14159;
  1816.              large = 1.23456789e10;
  1817.  
  1818.      printf will format floating point numbers: ``%w.df'' in
  1819. the format string will print the corresponding variable in a
  1820. field w digits wide, with d decimal places.  An e instead of
  1821. an f will produce exponential notation.
  1822.  
  1823. 27. Horrors! goto's and labels
  1824.  
  1825.      C has a goto statement and labels, so  you  can  branch
  1826. about  the  way  you  used  to.  But most of the time goto's
  1827. aren't needed.  (How many have we used up  to  this  point?)
  1828. The  code  can  almost  always  be more clearly expressed by
  1829. for/while, if/else, and compound statements.
  1830.  
  1831.      One use of goto's with some legitimacy is in a  program
  1832. which  contains  a  long loop, where a while(1) would be too
  1833. extended.  Then you might write
  1834.  
  1835.         mainloop:
  1836.              ...
  1837.              goto mainloop;
  1838.  
  1839. Another use is to implement a break out  of  more  than  one
  1840. level  of  for  or  while.  goto's can only branch to labels
  1841. within the same function.
  1842.  
  1843. 28. Acknowledgements
  1844.  
  1845.      I am indebted to a veritable host of readers  who  made
  1846. valuable  criticisms  on  several  drafts  of this tutorial.
  1847. They ranged in experience from  complete  beginners  through
  1848. several  implementors  of  C  compilers  to  the  C language
  1849. designer himself.  Needless to say, this is  a  wide  enough
  1850. spectrum of opinion that no one is satisfied (including me);
  1851. comments and suggestions are still  welcome,  so  that  some
  1852. future version might be improved.
  1853.  
  1854. References
  1855.  
  1856.      C is an extension of B, which was  designed  by  D.  M.
  1857. Ritchie  and  K. L. Thompson [4].  The C language design and
  1858. UNIX implementation are the work of D. M. Ritchie.  The GCOS
  1859. version  was  begun  by A. Snyder and B. A. Barres, and com-
  1860. pleted by S. C. Johnson and M. E. Lesk.  The IBM version  is
  1861. primarily  due  to T. G. Peterson, with the assistance of M.
  1862. E. Lesk.
  1863.  
  1864. [1]   D. M. Ritchie, C Reference Manual.   Bell  Labs,  Jan.
  1865.      1974.
  1866.  
  1867. [2]   M. E. Lesk & B. A. Barres, The  GCOS  C  Library.
  1868.           Bell Labs, Jan. 1974.
  1869.  
  1870. [3]   D.  M.   Ritchie   &   K.   Thompson,  UNIX Programmer's
  1871.       Manual.  5th Edition, Bell Labs, 1974.
  1872.  
  1873. [4]   S. C. Johnson & B.  W.  Kernighan,  The Programming
  1874.       Language  B.  Computer Science  Technical  Report  8,
  1875.       Bell  Labs, 1972.